<template>
  <div class="contentTable" id="contentTable" v-show="resData.length > 0">
    <div class="ant-spin-container" v-if="tableShow">
      <div
        v-for="(item, index) in resData"
        class="tablebox"
        :data-row-key="item.id"
        :key="item"
      >
        <div class="content-top">
          <div class="left-title">
            <a-checkbox
              @click="checkedClick(item.checked, index)"
              v-model:checked="item.checked"
            ></a-checkbox>
            <div class="title-box">
              <span class="channelName_title">
                <a @click.stop="selectColumn(item)">
                  <p class="channelName-content">{{ "[" + item.channelName + "]" }}</p>
                </a>
                <p
                  class="title-text"
                  @click.stop="eidtRecord(item)"
                  v-if="item.title.length + item.channelName.length < titleLength"
                >
                  {{ handleTitle(item.title, item.channelName) }}
                </p>
                <a-tooltip v-else>
                  <template #title>
                    <p class="title-text">
                      {{ handleTitle(item.title, item.channelName) }}
                    </p>
                  </template>
                  <p class="title-text" @click.stop="eidtRecord(item)">
                    {{ handleTitle(item.title, item.channelName) }}
                  </p>
                </a-tooltip>
              </span>

              <a-tooltip v-if="item.isTop">
                <template #title>已置顶</template>
                <i
                  class="iconfont icon-a-Pinnedtotop1"
                  style="margin-right: 4px; color: #1f6ded"
                ></i>
              </a-tooltip>
              <a-tooltip v-for="type in item.types">
                <template #title>{{ type?.typeName }}</template>
                <img :src="type?.logoUrl" alt="" class="tabletypeImg" />
              </a-tooltip>
            </div>
            <!-- <span v-else>{{ item.xwly }}</span> -->
          </div>
          <div class="right-msg">
            <p>
              <span>创建人：</span>
              <span>{{ item.createUser }}</span>
            </p>
            <p style="margin-left: 24px">
              <span>发布时间：</span>
              <span>{{ item.publishTime }}</span>
            </p>
          </div>
        </div>
        <div class="content-bottom">
          <div class="left-status">
            <span class="anytype" :class="'type' + item.status">{{
              getRecordValue(item.status)
            }}</span>
            <div class="popularity">
              <p>
                <i class="iconfont icon-preview"></i>
                <span>{{ item.views }}</span>
              </p>
              <p>
                <i class="iconfont icon-a-Firstpush"></i>
                <span>{{ item.likes }}</span>
              </p>
              <p>
                <i class="iconfont icon-collect"></i>
                <span>{{ item.visitors }}</span>
              </p>
              <p>
                <i class="iconfont icon-comment1"></i>
                <span>{{ item.comments }}</span>
              </p>
            </div>
          </div>
          <div class="right-operation-btns">
            <a
              class="eidtRecords"
              v-if="item.status != 3 && item.status != 5 && item.status != 6"
              :class="{ disable: !btnPerm.includes('publishAble') }"
              @click.stop="releaseRecord(item)"
              >发布</a
            >
            <a class="eidtRecords" @click.stop="eidtRecord(item)"> 详情</a>
            <a
              v-if="item.status != 3"
              class="eidtRecords"
              :class="{
                disable: item.isTop
                  ? !btnPerm.includes('cancelTopAble')
                  : !btnPerm.includes('topAble'),
              }"
              @click.stop="singleHandleTop(item)"
              >{{ item.isTop ? "取消置顶" : "置顶" }}</a
            >
            <a
              class="eidtRecords"
              :class="{ disable: !btnPerm.includes('offlineAble') }"
              @click.stop="offlineRecord(item)"
              v-if="item.status == 5"
              >下线</a
            >
            <a-popover
              placement="bottomRight"
              v-if="item.status != 3"
              overlayClassName="contentType_pop"
            >
              <template #content>
                <a-checkbox-group
                  :value="item.types && item.types.map((obj: any) => obj.id)"
                  :disabled="!btnPerm.includes('editContentTypeAble')"
                  class="contentTypeImg"
                >
                  <a-checkbox
                    v-for="checkItem in props.contentData"
                    :value="checkItem.id"
                    class="checkboxs"
                    @change="checkboxs($event, checkItem, index)"
                  >
                    <div class="typeImgBox">
                      <img :src="checkItem.logoUrl" alt="" class="typeImg" />
                      <span>{{ checkItem.typeName }}</span>
                    </div>
                  </a-checkbox>
                </a-checkbox-group>
              </template>
              <a
                class="eidtRecords more"
                :class="{ disable: !btnPerm.includes('editContentTypeAble') }"
                >内容类型</a
              >
            </a-popover>
            <a
              class="eidtRecords"
              v-if="item.status == 3"
              @click.stop="auditProgress(item)"
              >审核进度</a
            >
            <a class="eidtRecords" @click.stop="urgeRecords(item)" v-if="item.status == 3"
              >审核催办</a
            >
            <a
              class="eidtRecords"
              @click.stop="revocationRecords(item)"
              v-if="item.status == 3"
              >撤回审核</a
            >
            <a-popconfirm
              :disabled="!btnPerm.includes('deleteAble')"
              v-if="item.status != 3"
              placement="topRight"
              @confirm="fetchContentRecycle([item.id])"
              class="eidtRecords"
            >
              <template #title>
                <p style="width: 197px">是否将此内容移入回收站？</p>
              </template>
              <a :class="{ disable: !btnPerm.includes('deleteAble') }">删除</a>
            </a-popconfirm>

            <a
              class="eidtRecords"
              @click.stop="viewPage(item.previewUrl, 1)"
              :class="{ disable: !item.previewUrl || !btnPerm.includes('previewAble') }"
              >预览</a
            >
            <a
              class="eidtRecords"
              v-if="item.scanUrl"
              :class="{
                disable:
                  !item.scanUrl || item.status != 5 || !btnPerm.includes('scanAble'),
              }"
              @click.stop="viewPage(item.scanUrl, 2)"
              >浏览</a
            >
            <a
              class="eidtRecords"
              @click.stop="pushRecord(item)"
              :class="{ disable: !btnPerm.includes('pushAble') }"
              v-if="item.status == 5"
              >推送</a
            >
            <template v-if="!isShowMore">
              <a
                class="eidtRecords"
                :class="{ disable: !btnPerm.includes('moveAble') }"
                @click.stop="moveRecords(item)"
                v-if="item.status != 3"
                >移动</a
              >
              <a
                class="eidtRecords"
                :class="{ disable: !btnPerm.includes('archiveAble') }"
                @click.stop="singleMergeDom(item)"
                v-if="item.status != 3"
                >归档</a
              >
              <a
                class="eidtRecords"
                @click.stop="historyRecord(item)"
                :class="{ disable: !btnPerm.includes('scanHistoryAble') }"
                v-if="item.status == 5 || item.status == 7"
                >浏览记录</a
              >
              <a
                class="eidtRecords"
                :class="{ disable: !btnPerm.includes('relatedContentAble') }"
                @click.stop="correlationRecord(item)"
                v-if="item.status != 3"
                >相关内容</a
              >
              <a
                class="eidtRecords"
                :class="{ disable: !btnPerm.includes('operationHistoryAble') }"
                @click.stop="operatingRecord(item)"
                v-if="item.status != 3"
                >操作记录</a
              >
            </template>
            <a-popover
              placement="bottomRight"
              v-if="isShowMore && item.status != 3"
              overlayClassName="a-content-btns-popover"
            >
              <template #content>
                <a
                  class="eidtRecords"
                  :class="{ disable: !btnPerm.includes('moveAble') }"
                  @click.stop="moveRecords(item)"
                  v-if="item.status != 3"
                  >移动</a
                >
                <a
                  class="eidtRecords"
                  :class="{ disable: !btnPerm.includes('archiveAble') }"
                  @click.stop="singleMergeDom(item)"
                  v-if="item.status != 3"
                  >归档</a
                >
                <a
                  class="eidtRecords"
                  @click.stop="historyRecord(item)"
                  :class="{ disable: !btnPerm.includes('scanHistoryAble') }"
                  v-if="item.status == 5 || item.status == 7"
                  >浏览记录</a
                >
                <a
                  v-if="item.status != 3"
                  class="eidtRecords"
                  :class="{ disable: !btnPerm.includes('relatedContentAble') }"
                  @click.stop="correlationRecord(item)"
                  >相关内容</a
                >
                <a
                  v-if="item.status != 3"
                  class="eidtRecords"
                  :class="{ disable: !btnPerm.includes('operationHistoryAble') }"
                  @click.stop="operatingRecord(item)"
                  >操作记录</a
                >
              </template>
              <a class="more">...</a>
            </a-popover>
          </div>
        </div>
      </div>
    </div>
    <pagination
      :pageSize="pageSize"
      :pageCurrent="pageCurrent"
      :dataSource="props.configData.records"
      @selectAll="selectAll"
      @changePage="changePage"
      :isSelect="true"
      :selfChecked="isSelectAll"
      :total="props.configData.total"
      :isShowPagination="isShowPagination"
      :simple="true"
      :height="0"
      :showCheckDelete="showCheckDelete"
      :scroll="scroll"
      class="paginations"
      ref="tagBaseTables"
      v-if="resData.length > 0"
    >
      <template #opration>
        <a-dropdown
          :disabled="!rowSelection.length"
          :placement="scroll.isFixed ? 'top' : 'bottom'"
        >
          <template #overlay>
            <a-menu @click="handleMenuClick">
              <a-menu-item key="3" :disabled="!btnPerm.includes('moveAble')">
                移动
              </a-menu-item>
              <!-- <a-menu-item key="4"> 排序 </a-menu-item> -->
              <a-menu-item key="5" :disabled="!btnPerm.includes('pushAble')">
                推送
              </a-menu-item>
              <a-menu-item key="6" :disabled="!btnPerm.includes('archiveAble')">
                归档
              </a-menu-item>
            </a-menu>
          </template>
          <a-button :style="{ 'margin-left': '8px' }">
            内容操作
            <DownOutlined />
          </a-button>
        </a-dropdown>
        <a-popover
          placement="topRight"
          v-if="rowSelection.length"
          overlayClassName="contentType_pop"
        >
          <template #content>
            <a-checkbox-group
              v-model:value="contType"
              :disabled="!btnPerm.includes('editContentTypeAble')"
              class="contentTypeImg"
            >
              <a-checkbox
                v-for="checkItem in props.contentData"
                :value="checkItem.id"
                class="checkboxs"
                @change="contTypeChek"
              >
                <div class="typeImgBox">
                  <img :src="checkItem.logoUrl" alt="" class="typeImg" />
                  <span>{{ checkItem.typeName }}</span>
                </div>
              </a-checkbox>
            </a-checkbox-group>
          </template>
          <a-button
            :disabled="!btnPerm.includes('editContentTypeAble')"
            :style="{ 'margin-left': '8px' }"
            >内容类型
            <DownOutlined />
          </a-button>
        </a-popover>
        <a-dropdown v-else>
          <template #overlay>
            <a-menu> </a-menu>
          </template>
          <a-button :disabled="!rowSelection.length" :style="{ 'margin-left': '8px' }">
            内容类型
            <DownOutlined />
          </a-button>
        </a-dropdown>
        <!-- <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
            >内容类型</a-button
          > -->

        <a-button
          :style="{ 'margin-left': '8px' }"
          @click="deleteSelectedAll"
          :disabled="!rowSelection.length || !btnPerm.includes('deleteAble')"
          >删除</a-button
        >
        <a-button
          v-show="scroll.isFixed"
          :style="{ 'margin-left': '8px' }"
          @click="publishAll()"
          :disabled="!rowSelection.length || !btnPerm.includes('publishAble')"
          >发布</a-button
        >
        <a-button
          v-show="scroll.isFixed"
          :style="{ 'margin-left': '8px' }"
          @click="offlineRecordAll()"
          :disabled="!rowSelection.length || !btnPerm.includes('offlineAble')"
          >下线</a-button
        >
        <a-button
          v-show="scroll.isFixed"
          :style="{ 'margin-left': '8px' }"
          @click="handleMenuClick({ key: 1 })"
          :disabled="!rowSelection.length || !btnPerm.includes('topAble')"
          >置顶</a-button
        >
        <a-button
          v-show="scroll.isFixed"
          :style="{ 'margin-left': '8px' }"
          @click="handleMenuClick({ key: 2 })"
          :disabled="!rowSelection.length || !btnPerm.includes('cancelTopAble')"
          >取消置顶</a-button
        >
      </template>
    </pagination>
    <contentMove
      v-if="isMoveVisible"
      :isVisible="isMoveVisible"
      :contentIds="contentId"
      :channelId="selectChannelId"
      @handleOk="handleOk"
      @handleCancle="isMoveVisible = false"
    ></contentMove>
    <contentPush
      v-if="isPushVisible"
      :isVisible="isPushVisible"
      :contentIds="contentId"
      :disableCheckbox="disableCheckboxId"
      @handleOk="handleOk"
      @handleCancle="isPushVisible = false"
    ></contentPush>
    <browsingHistory
      v-if="isHistoryVisible"
      :isVisible="isHistoryVisible"
      :contentIds="contentId"
      @handleOk="handleOk"
      @handleCancle="isHistoryVisible = false"
    ></browsingHistory>
    <sortModel
      v-if="isSortVisible"
      :isVisible="isSortVisible"
      :contentIds="contentId"
      @handleOk="handleOk"
      @handleCancle="isSortVisible = false"
    ></sortModel>
    <correlationModel
      v-if="isCorrelationVisible"
      :isVisible="isCorrelationVisible"
      :contentId="contentIdDetail"
      @handleOk="handleOk"
      @handleCancle="isCorrelationVisible = false"
    ></correlationModel>
    <operatingRecordmodel
      v-if="isoperatingVisible"
      :isVisible="isoperatingVisible"
      @handleCancle="isoperatingVisible = false"
      :contentId="contentIdDetail"
    ></operatingRecordmodel>
  </div>
  <a-empty v-show="!resData.length" />
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, createVNode, computed, watch } from "vue";
import { UserOutlined, DownOutlined } from "@ant-design/icons-vue";
import treeTable from "@/components/table/baseTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import contentMove from "./contentMove.vue";
import contentPush from "./contentPush.vue";
import browsingHistory from "./browsingHistory.vue";
import sortModel from "./sortModel.vue";
import { scrollType } from "@/type.d";
import { useRouter } from "vue-router";
import pagination from "@/components/pagination/index.vue";
import Sortable from "sortablejs";
import { getTableScroll } from "@/components/table/tableConfig/table";
import { Modal, message } from "ant-design-vue";
import { dataSourceType, detailDataItemType } from "@/type";
import request from "@/api/index";
import operatingRecordmodel from "./newContent/operatingRecord.vue";
import correlationModel from "./newContent/correlationModel.vue";
import { number } from "echarts";
import { cloneDeep } from "lodash";
import { routerPerm } from "@/utils/common";
import { Item } from "ant-design-vue/lib/menu";
const btnPerm = ref<any[]>([]);
const props = defineProps({
  configData: {
    type: Object,
    default: {},
  },
  isOpen: {
    type: Boolean,
    default: true,
  },
  pageSize: {
    type: Number,
    default: 20,
  },
  pageCurrent: {
    type: Number,
    default: 1,
  },
  contentData: {
    default: [] as any[],
  },
  channelId: {
    type: [Number, String],
    default: null,
  },
});
const isShowPagination = ref<boolean>(true); // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义
const isSelectAll = ref<boolean>(false); // 是否需要配分页器
const isMoveVisible = ref(false); //控制是否展示移动对话框
const isPushVisible = ref(false); //控制是否展示推送对话框
const isHistoryVisible = ref(false); //控制是否展示浏览记录对话框
const isSortVisible = ref(false); //控制是否展示排序对话框
const isCorrelationVisible = ref(false); //控制是否展示相关内容对话框
let isoperatingVisible = ref(false); //控制是否展示操作记录对话框
const selectList = ref<any[]>([]);
let tableShow = ref<Boolean>(false); // 表格显示隐藏，用于refresh数据用的
const router = useRouter();
const contentId = ref<any[]>([]);
const tagBaseTables = ref<any>(null);
const contType = ref<any[]>([]);
const contentIdDetail = ref<number>(0);
const isShowMore = ref<boolean>(false);
const isShowHiddTitle = ref<boolean>(false);
let rowSelection = ref<(string | number)[]>([]);
const disableCheckboxId = ref<any>(null);
// 当前页和数量
const pageCurrent = ref<number>(props.configData.current || 1);
const pageSize = ref<number>(props.configData.size || 20);

let dataList = ref<dataSourceType[]>([]); //表格数据源
let selectedRowKeys = ref<dataSourceType[]>([]); // 选中的列表id集合
const resData = ref(cloneDeep(props.configData.records));
let scroll: scrollType = reactive({ y: "", isFixed: false });
let titleLength = ref(40);
const isCanEdit = ref<boolean>(true);
const selectChannelId = ref<any>(null);
//watch
watch(
  () => [props.configData.size, props.configData.current],
  ([size, current]) => {
    pageSize.value = size;
    pageCurrent.value = current;
  }
);
watch(
  () => props.channelId,
  (newVal, oldVal) => {
    selectChannelId.value = newVal;
  },
  { deep: true }
);
// computed
rowSelection = computed(() => {
  return selectList.value;
});

//computed
dataList = computed(() => {
  return JSON.parse(JSON.stringify(resData.value));
});
// 多选修改内容类型
const contTypeChek = () => {
  if (!btnPerm.value.includes("editContentTypeAble")) return;
  contentId.value = selectList.value;
  nextTick(() => {
    fetchContentChangeTypes(contType.value, contentId.value);
    emit("changePage", {
      pageCurrent: pageCurrent.value,
      pageSize: pageSize.value,
    });
    nextTick(() => {
      selectList.value = [];
    });
  });
};
// 修改内容类型
const checkboxs = (item: any, checkItem: any, index: any) => {
  if (!btnPerm.value.includes("editContentTypeAble")) return;
  resData.value[index].types
    ? resData.value[index].types
    : (resData.value[index].types = []);
  if (item.target.checked) {
    resData.value[index].types.push(checkItem);
  } else {
    let lsit = resData.value[index].types;
    lsit.forEach((data: any, indexs: any) => {
      if (checkItem.id == data.id) {
        resData.value[index].types.splice(indexs, 1);
      }
    });
  }
  fetchContentChangeTypes(
    resData.value[index].types.map((obj: any) => obj.id),
    [resData.value[index].id]
  );
  nextTick(() => {
    emit("changePage", {
      pageCurrent: pageCurrent.value,
      pageSize: pageSize.value,
    });
  });
};

//拖拽相关

const refreshTable = () => {
  tableShow.value = false;
  nextTick(() => {
    tableShow.value = true;
    nextTick(() => {
      inintDrag();
    });
  });
};

const inintDrag = () => {
  let sortDom = document.querySelector(`#contentTable .ant-spin-container`);
  let dragged: dataSourceType[] = [];
  let related: dataSourceType[] = [];
  let IsCanDrag: boolean = true;
  let Oldindex: any = 0;

  Sortable.create(sortDom as HTMLElement, {
    disabled: false,
    //sort:true, // 给了就无法拖动
    //handle: ".tablebox",
    animation: 250,
    draggable: ".tablebox", // tr拖动
    dragClass: "dragClass",
    dataIdAttr: "chosenClass", //给停靠位置添加的class（可以给这个class定义样式
    ghostClass: "ghostClass",
    forceFallback: false,
    fallbackClass: "sortable-fallback", // 当使用forceFallback的时候，被复制的dom的css类名
    onStart({ item }) {
      let targetRowKey = item.dataset.rowKey;
      resData.value.filter((item: any, index: number) => targetRowKey == item.id)[0] ||
        [];
      dataList.value.forEach((item_data: any, index: number) => {
        if (targetRowKey == item_data.id) {
          Oldindex = index;
        }
      });
    },
    onMove(evt) {
      dragged = resData.value.filter(
        (item: any) => evt.dragged.dataset.rowKey == item.id
      );
      related = resData.value.filter(
        (item: any) => evt.related.dataset.rowKey == item.id
      );

      if (
        (dragged[0]?.isTop && !related[0]?.isTop) ||
        (!dragged[0]?.isTop && related[0]?.isTop)
      ) {
        IsCanDrag = false;
        return false;
      } else {
        IsCanDrag = true;
      }
    },
    onEnd: ({ newIndex, item }: { newIndex: any; item: any }) => {
      let Targetindex: number = newIndex; // 拖拽的元素和第Targetindex个子元素将要互换位置

      if (!(dragged[0]?.id && related[0]?.id)) {
        return;
      }

      if (!IsCanDrag) {
        // refreshTable();
        //message.warning("不可拖拽互换位置！！");
        return;
      } else {
        let draggData: any = {
          id: dragged[0]?.id,
          toId: related[0]?.id,
          isBefore: Oldindex > Targetindex,
          data: JSON.parse(JSON.stringify(dataList.value)),
        };
        if (dragged[0]?.id && related[0]?.id) {
          dragEnd(draggData);
        }
      }

      // message.success("拖拽互换位置成功！！");
    },
  });
};

// 拖拽变换表格数据
const dragEnd = async (param: dataSourceType) => {
  const contentIds = param.data.length && param.data.map((item: any) => item.id);
  await request
    .getContentDragSort({ ...param, contentIds })
    .then((res: dataSourceType) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        let prs = {
          pageCurrent: pageCurrent.value,
          pageSize: pageSize.value,
        };
        changePage(prs);
        refreshTable();
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

const getTargeIndex: any = (list: dataSourceType[], id: string | number, arr = []) => {
  return list.reduce((total: any, item, index) => {
    if (item.id.toString() === id) {
      return [...total, index];
    } else {
      if (item.children && item.children.length) {
        let childArr = getTargeIndex(item.children, id, [...arr, index]);
        if (childArr.length === [...arr, index].length) {
          childArr = total;
        }
        return childArr;
      } else {
        return total;
      }
    }
  }, arr);
};
//单选
const checkedClick = (item: any, index: number) => {
  selectList.value = [];
  resData.value[index].checked = !item;
  nextTick(() => {
    isSelectAll.value = resData.value.every((item: any) => item.checked == true);
    resData.value.map((item: any) => {
      if (item.checked) {
        selectList.value.push(item.id);
      }
    });
  });
};
// 全选
const selectAll = () => {
  selectList.value = [];
  isSelectAll.value = !isSelectAll.value;
  resData.value.map((item: any) => {
    item.checked = isSelectAll.value;
    if (item.checked) {
      selectList.value.push(item.id);
    }
  });
};

// 相关内容
const correlationRecord = (item: any) => {
  if (!btnPerm.value.includes("relatedContentAble")) return;
  contentIdDetail.value = item.id;
  isCorrelationVisible.value = true;
};
// 操作记录
const operatingRecord = (item: any) => {
  if (!btnPerm.value.includes("operationHistoryAble")) return;
  contentIdDetail.value = item.id;
  isoperatingVisible.value = true;
};

//发布
const releaseRecord = async (item: any) => {
  if (!btnPerm.value.includes("publishAble")) return;
  Modal.confirm({
    content: "您确定发布此内容？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "发布",
    onOk: async () => {
      fetchContentPublish([item.id]);
    },
    onCancel() {},
  });
};

//批量发布
const publishAll = async () => {
  Modal.confirm({
    content: "您确定发布选中的内容？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "发布",
    onOk: async () => {
      fetchContentPublish(rowSelection.value);
    },
    onCancel() {},
  });
};

//批量下线
const offlineRecordAll = async () => {
  Modal.confirm({
    content: "您确定下线选中的内容？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "下线",
    onOk: async () => {
      fetchContentOffline(rowSelection.value);
    },
    onCancel() {},
  });
};
//下线
const offlineRecord = async (item: any) => {
  if (!btnPerm.value.includes("offlineAble")) return;
  Modal.confirm({
    content: "您确定下线此内容？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "下线",
    onOk: async () => {
      fetchContentOffline([item.id]);
    },
    onCancel() {},
  });
};
// 查看审核进度
const auditProgress = (item: any) => {
  let params = {
    contentId: item.id,
  };
  request.auditProgress(params).then((res: any) => {
    if (res) {
      router.push({
        path: "/config/workFlow/auditDetail",
        query: {
          id: res,
        },
      });
    }
  });
};
// 催办
const urgeRecords = async (item: any) => {
  Modal.confirm({
    content: "催办当前审核节点的审核用户，将以站内信或邮件或短信的形式通知到对应审核用户",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "催办",
    onOk: async () => {
      let params = {
        id: item.id,
      };
      request.contentUrge(params).then((res: any) => {
        if (res.code == "00000 00000") {
          let prs = {
            pageCurrent: pageCurrent.value,
            pageSize: pageSize.value,
          };
          changePage(prs);
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      });
    },
    onCancel() {},
  });
};
// 撤回审核
const revocationRecords = async (item: any) => {
  let params = {
    id: item.id,
  };
  Modal.confirm({
    title: "是否撤回审核？",
    content: "撤回审核后，需要重新发起审核，是否继续？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "撤回审核",
    onOk: async () => {
      //revokeWorkflow
      request.revokeWorkflow(params).then((res: any) => {
        if (res.code == "00000 00000") {
          let prs = {
            pageCurrent: pageCurrent.value,
            pageSize: pageSize.value,
          };
          changePage(prs);
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      });
    },
    onCancel() {},
  });
};
// 删除多个
const deleteSelectedAll = async (item: any) => {
  Modal.confirm({
    content: "您确定将选中的内容移入回收站？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      fetchContentRecycle(selectList.value);
    },
    onCancel() {},
  });
};

// 下线
const fetchContentOffline = async (ids: any) => {
  request
    .fetchContentOffline({ ids })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        let prs = {
          pageCurrent: pageCurrent.value,
          pageSize: pageSize.value,
        };
        changePage(prs);
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

// 发布
const fetchContentPublish = async (ids: any) => {
  request
    .fetchContentPublish({ ids })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        let prs = {
          pageCurrent: pageCurrent.value,
          pageSize: pageSize.value,
        };
        changePage(prs);
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// 更改内容类型
const fetchContentChangeTypes = async (data: any, contentIds: any) => {
  request
    .fetchContentChangeTypes({ typeIds: data, contentIds: contentIds })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        // let prs = {
        //   pageCurrent: pageCurrent.value,
        //   pageSize: pageSize.value,
        // };
        // changePage(prs);
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// 删除
const fetchContentRecycle = async (data: any) => {
  request
    .fetchContentRecycle({ ids: data })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        let prs = {
          pageCurrent: pageCurrent.value,
          pageSize: pageSize.value,
        };
        isSelectAll.value = true;
        selectAll();
        changePage(prs);
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

// 单个置顶和取消置顶
const singleHandleTop = (item: any) => {
  if (item.isTop) {
    if (!btnPerm.value.includes("cancelTopAble")) return;
  } else {
    if (!btnPerm.value.includes("topAble")) return;
  }
  selectList.value = [item.id];
  handleMenuClick({ key: item.isTop ? 2 : 1 });
};
// 单个归档
const singleMergeDom = (item: any) => {
  if (!btnPerm.value.includes("archiveAble")) return;
  selectList.value = [item.id];
  handleMenuClick({ key: 6 });
};

//按钮操作
const handleMenuClick = async (params: any) => {
  if (params.key == 1) {
    // 置顶;
    request
      .fetchContentTop({ ids: selectList.value })
      .then((res: any) => {
        if (res.code == "00000 00000") {
          let prs = {
            pageCurrent: pageCurrent.value,
            pageSize: pageSize.value,
          };
          changePage(prs);
          message.success(res.message);
          nextTick(() => {
            selectList.value = [];
          });
        } else {
          message.error(res.message);
        }
      })
      .catch((err: any) => {
        throw new Error(err);
      });
  } else if (params.key == 2) {
    // 取消置顶;
    request
      .fetchContentTopCancell({ ids: selectList.value })
      .then((res: any) => {
        if (res.code == "00000 00000") {
          let prs = {
            pageCurrent: pageCurrent.value,
            pageSize: pageSize.value,
          };
          changePage(prs);
          message.success(res.message);
          nextTick(() => {
            selectList.value = [];
          });
        } else {
          message.error(res.message);
        }
      })
      .catch((err: any) => {
        throw new Error(err);
      });
  } else if (params.key == 3) {
    // 移动;
    isMoveVisible.value = true;
    contentId.value = selectList.value;
  } else if (params.key == 4) {
    // 排序;
    isSortVisible.value = true;
    contentId.value = selectList.value;
  } else if (params.key == 5) {
    // 推送;
    isPushVisible.value = true;
    contentId.value = selectList.value;
  } else if (params.key == 6) {
    // 归档;
    Modal.confirm({
      content: "您确定归档选中的内容？",
      centered: true,
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",
      }),
      cancelText: "取消",
      okText: "确定",
      onOk: async () => {
        request
          .fetchContentFile({ ids: selectList.value })
          .then((res: any) => {
            if (res.code == "00000 00000") {
              let prs = {
                pageCurrent: pageCurrent.value,
                pageSize: pageSize.value,
              };
              changePage(prs);
              message.success(res.message);
              nextTick(() => {
                selectList.value = [];
              });
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      },
      onCancel() {},
    });
  }
};
// 移动
const moveRecords = async (item: any) => {
  if (!btnPerm.value.includes("moveAble")) return;
  isMoveVisible.value = true;
  contentId.value = [item.id];
};
// 推送
const pushRecord = async (item: any) => {
  if (!btnPerm.value.includes("pushAble")) return;
  isPushVisible.value = true;
  contentId.value = [item.id];
  disableCheckboxId.value = item.channelId
};
// 浏览记录
const historyRecord = async (item: any) => {
  if (!btnPerm.value.includes("scanHistoryAble")) return;
  isHistoryVisible.value = true;
  contentId.value = [item.id];
};

// 确认移动 推送
const handleOk = (e: any) => {
  isMoveVisible.value = false;
  if (e && e.text === "推送") {
    isPushVisible.value = false;
  }
  let prs = {
    pageCurrent: pageCurrent.value,
    pageSize: pageSize.value,
  };
  changePage(prs);
  nextTick(() => {
    selectList.value = [];
  });
};
const selectColumn = (item: any) => {
  emit('selectColumn', [item.channelId])
};
// 详情
const eidtRecord = async (item: any) => {
  router.push({
    path: "/content/newContent",
    name: "内容详情",
    query: {
      contentId: item.id,
      channelId: item.channelId,
      id: item.modelId,
      modelName: item.modelName,
      previewPerm: !btnPerm.value.includes("previewAble") ? 1 : 0, // 1 没有按钮权限 0 有
    },
  });
};

//处理标题显示的方法
const handleTitle = (title: string = "", channelName: string = "") => {
  if (
    !isShowHiddTitle.value &&
    title?.length + channelName?.length > 40 &&
    channelName?.length < 40
  ) {
    return title.slice(0, 40 - channelName.length) + "...";
  } else if (
    isShowHiddTitle.value &&
    title?.length + channelName?.length > 25 &&
    channelName?.length < 25
  ) {
    return title.slice(0, 25 - channelName?.length) + "...";
  } else {
    return title;
  }
};

// 删除单个
const confirmDelete = async (item: any) => {
  // deleteArr.value = [item.id];
  // deleteRecords(deleteArr.value);
};

const emit = defineEmits(["changePage", "selectColumn"]);
//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  emit("changePage", data);
  pageCurrent.value = data.pageCurrent;
  pageSize.value = data.pageSize;
  selectList.value = [];
};
// 页面浏览
const viewPage = (item: any, type: number) => {
  if (type === 1 && item && btnPerm.value.includes("previewAble")) {
    window.open(item);
  } else if (type === 2 && item && btnPerm.value.includes("scanAble")) {
    window.open(item);
  } else {
    return;
  }
};
const getRecordValue = (key: number) => {
  return key == 1
    ? "草稿"
    : key == 3
    ? "审核中"
    : key == 4
    ? "待发布"
    : key == 5
    ? "已发布"
    : key == 6
    ? "审核不通过"
    : key == 7
    ? "已下线"
    : key == 8 && "归档";
};

//watch
// watch(
//   () => contType.value,
//   (newVal, oldVal) => {
//     fetchContentChangeTypes(newVal, contentId.value);
//   },
//   { deep: true }
// );
watch(
  () => props.configData.records,
  (newVal, oldVal) => {
    if (newVal.length) {
      resData.value = cloneDeep(newVal);
      isSelectAll.value = resData.value.every((item: any) => item.checked == true);
      nextTick(() => {
        let obj = getTableScroll(117, "contentTable", 40);
        scroll.y = obj.y;
        scroll.isFixed = obj.isFixed;
      });
    } else {
      resData.value = [];
      isSelectAll.value = false;
    }
  },
  { deep: true }
);

//onMounted
onMounted(() => {
  btnPerm.value = routerPerm();

  isShowMore.value = document.documentElement.clientWidth <= 1600 ? true : false;
  isShowHiddTitle.value = document.documentElement.clientWidth <= 1440 ? true : false;
  window.onresize = () => {
    isShowMore.value = document.documentElement.clientWidth <= 1600 ? true : false;
    isShowHiddTitle.value = document.documentElement.clientWidth <= 1440 ? true : false;
  };
  tableShow.value = true;
  nextTick(() => {
    let obj = getTableScroll(117, "contentTable", 40);
    scroll.y = obj.y;
    scroll.isFixed = obj.isFixed;
    inintDrag();
  });
  pageSize.value = props.pageSize;
  pageCurrent.value = props.pageCurrent;
  if (document.body.offsetWidth < 1366) {
    titleLength.value = 18;
  } else if (document.body.offsetWidth < 1600) {
    titleLength.value = 25;
  } else {
    titleLength.value = 40;
  }
});
</script>

<style lang="less" scoped>
.dragClass {
  background-color: #fff;
}

.chosenClass {
  background-color: blue;
}

.ghostClass {
  background-color: #00000005;
}

.ant-empty {
  margin-top: 60px;
}

.contentTable {
  background-color: #fff;
  flex: 1;

  .tablebox {
    // margin: 0 5px;
    cursor: move;
    display: flex;
    flex-direction: column;
    margin-left: 16px;
    margin-right: 16px;
    padding-top: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.06);
    border-radius: 2px;
    moz-user-select: -moz-none;
    -moz-user-select: none;
    -o-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;

    &:hover {
      background: #00000005;
      // margin: 0 2px;
      // // background: #ffffff;
      // padding: 16px;
      // box-shadow: 0px 5px 12px 4px rgba(0, 0, 0, 0.09),
      //   0px 3px 6px 0px rgba(0, 0, 0, 0.12), 0px 1px 2px -2px rgba(0, 0, 0, 0.16);
    }

    .imgs {
      img {
        width: 150px;
        height: 84px;
        border-radius: 2px;
        opacity: 1;
      }
    }

    .content-top {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      height: 16px;

      .left-title {
        display: flex;
        flex-direction: row;
        align-items: center;

        .title-box {
          display: flex;
          flex-direction: row;
          align-items: center;

          .channelName_title {
            display: flex;
          }

          .channelName-content {
            margin: 0 8px;
            font-size: 14px;
            color: #00000073;
            width: max-content;
          }

          .title-text {
            flex: 1;
            font-weight: 500;
            font-size: 14px;
            color: #000000d9;
            margin-right: 11px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .icon-a-Pinnedtotop1 {
            font-size: 18px;
            line-height: 18px;
          }

          .tabletypeImg {
            margin-right: 4px;
            width: 18px;
            height: 18px;
          }

          .title-text:hover {
            cursor: pointer;
            color: #1f6ded;
          }

          .title-text:active {
            color: #1f6ded;
          }
        }
      }

      .right-msg {
        display: flex;
        flex-direction: row;
        align-items: center;

        p {
          font-size: 14px;
          color: #00000073;
        }
      }
    }

    .content-bottom {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      margin-top: 15px;

      .left-status {
        margin-left: 24px;
        display: flex;
        flex-direction: row;
        align-items: center;

        .anytype {
          padding: 0 8px;
          height: 22px;
          font-size: 12px;
          line-height: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .type3 {
          background-color: #edf7ff;
          color: #1f6ded;
          border: 1px solid #9cccff;
        }

        .type5 {
          background-color: #f6ffed;
          color: #389e0d;
          border: 1px solid #b7eb8f;
        }

        .type7 {
          background-color: rgba(0, 0, 0, 0.04);
          color: rgba(0, 0, 0, 0.45);
          border: 1px solid rgba(0, 0, 0, 0.15);
        }

        .type1 {
          background-color: #e6fffb;
          color: #08979c;
          border: 1px solid #87e8de;
        }

        .type4 {
          background-color: #fff7e6;
          color: #d46b08;
          border: 1px solid #ffd591;
        }

        .type6 {
          background-color: #fff1f0;
          color: #cf1322;
          border: 1px solid #ffa39e;
        }

        .popularity {
          margin-left: 8px;
          display: flex;
          flex-direction: row;
          align-items: start;

          .iconfont {
            color: rgba(0, 0, 0, 0.45);
          }

          p {
            margin-left: 12px;

            span {
              margin-left: 6px;
              font-size: 14px;
              color: #00000073;
              line-height: 14px;
            }
          }
        }
      }

      .right-operation-btns {
        display: flex;
        flex-direction: row;
        align-items: center;

        .eidtRecords {
          font-size: 14px;
          margin-left: 16px;
        }

        .eidtRecords:hover {
          background: transparent;
        }

        .more {
          font-size: 14px;
          margin-left: 16px;
        }

        .eidtRecords :first-child {
          margin-left: 0;
        }
      }
    }
  }
}

.paginations {
  padding: 0 8px;
  // width: calc(100% + 48px);
  // position: absolute;
  // bottom: 24px;
}
</style>
<style lang="less">
.a-content-btns-popover .ant-popover-inner-content {
  padding: 4px 0;
  display: flex;
  flex-direction: column;
}

.a-content-btns-popover .ant-popover-inner-content .eidtRecords {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 80px;
  height: 32px;
  padding-left: 12px;
}

.eidtRecords:hover {
  background-color: #0000000a;
}

.disable {
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
  // pointer-events:none;
}

.contentType_pop {
  .ant-popover-inner-content {
    padding: 4px 12px;

    .ant-checkbox {
      top: 0.1em;
    }

    .typeImgBox img {
      margin-bottom: 4px;
    }

    .typeImgBox span {
      line-height: 32px;
      height: 32px;
    }
  }

  .ant-checkbox + span {
    padding-left: 8px;
    padding-right: 0;
  }
}

.tableFootContaienr {
  .ant-btn > span + .anticon {
    font-size: 10px;
  }
}

@media screen and (min-width: 1600px) {
  .channelName_title {
    max-width: 580px;
  }
}

@media screen and (max-width: 1599px) and (min-width: 1370) {
  .channelName_title {
    max-width: 372px;
  }
}

@media screen and (max-width: 1369px) {
  .channelName_title {
    max-width: 288px;
  }
}
</style>
